import React, { Component } from 'react'
import {Cproduct} from '../types/product'
import {connect} from 'react-redux'

interface IProps{
    item:Cproduct,
    changeNum:(id:number,num:number) => void,
    open:(id:number) => void,
    changeChecked:(id:number,checked:boolean) => void
}

class CarProduct extends Component <IProps>{
    render() {
        let {title,price,num,checked,id} = this.props.item;
        return (
            <div>
                <input type="checkbox" checked={checked} onChange={() => {this.props.changeChecked(id,!checked)}}/>
                <h5>{title}</h5>
                <span>价格:{price}</span>
                <div>
                    <button onClick={() => {this.changeNum(id,num,true)}}>-</button>
                    <span>{num}</span>
                    <button onClick={() => {this.changeNum(id,num,false)}}>+</button>
                </div>
            </div>
        )
    }

    //修改数量
    changeNum = (id:number,num:number,flag:boolean) => {
        if(flag){
            //减
            if(num > 1){
                num = num-1;
                this.props.changeNum(id,num);
            }else{
                //num 为1 打开弹窗
                this.props.open(id);
            }
        }else{
            //加
            num = num+1;
            this.props.changeNum(id,num);
        }
    }
}

let stateMapToProps = (state:any) => {
    return {
       
    }
}

let dispatchMapToProps = (dispatch:any) => {
    return {
        changeNum(id:number,num:number){
            dispatch({type:'CHANGE_NUM',id,num})
        },
        changeChecked(id:number,checked:boolean){
            dispatch({type:'CHANGE_CHECKED',id,checked})
        }
    }
}

export default connect(stateMapToProps,dispatchMapToProps)(CarProduct)